import logging
import time
import urllib.parse

import requests
from django.conf import settings
from django.shortcuts import redirect
from django.views.generic import View

from libs.utils import AttrDict
from libs.utils import json_response

logger = logging.getLogger(__name__)
wx_set = AttrDict(settings.SERVICES['WX_SET'])


class WxOAuthAuthorize(View):
    def get(self, request):
        ids = request.GET.get('ids')
        redirect_uri = f'https://api.mengshijiaoyu.com.cn/app/register?courseIds={ids}'
        auth_url = (
            'https://open.weixin.qq.com/connect/oauth2/authorize'
            f'?appid={settings.SERVICES["WX_SET"]["APP_ID"]}'
            f'&redirect_uri={urllib.parse.quote(redirect_uri)}'
            '&response_type=code'
            '&scope=snsapi_base'
            f'&state={int(time.time())}'  # 使用时间戳作为state，避免缓存
            '#wechat_redirect'
        )
        return redirect(auth_url)


class WxOAuthCallback(View):
    def get(self, request):
        """处理微信授权回调，获取openid"""
        code = request.GET.get('code')
        state = request.GET.get('state')
        logger.info(f"收到授权回调，code: {code}, state: {state}")

        if not code:
            logger.error("未获取到授权码")
            return json_response(error='未获取到授权码，请重新授权')

        # 通过code获取access_token和openid
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
        params = {
            'appid': settings.SERVICES["WX_SET"]["APP_ID"],
            'secret': settings.SERVICES["WX_SET"]["APP_SECRET"],
            'code': code,
            'grant_type': 'authorization_code'
        }

        response = requests.get(url, params=params, timeout=30)

        # 检查HTTP响应状态
        if response.status_code != 200:
            logger.error(f"微信接口HTTP错误: {response.status_code}, {response.text}")
            return json_response(error=f'微信接口HTTP错误: {response.status_code}，请重新授权')

        res = response.json()
        logger.info(f"微信接口响应: {res}")

        if 'openid' in res:
            logger.info(f"成功获取openid: {res['openid']}")

            return json_response({
                'openid': res['openid']
            })

        error_msg = res.get('errmsg', '获取openid失败')
        logger.error(f"获取openid失败: {error_msg}")
        return json_response(error=error_msg)
